<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function sleep(delay) {
        let curr = Date.now();
        while (Date.now() - curr < delay) {}
        // for (var start = Date.now(); Date.now() - start <= delay; ) {}
      }
      const works = [
        () => {
          console.log('第一个任务开始');
          sleep(20);
          console.log('第一个任务结束');
        },
        () => {
          console.log('第二个任务开始');
          sleep(20);
          console.log('第二个任务结束');
        },
        () => {
          console.log('第三个任务开始');
          sleep(20);
          console.log('第三个任务结束');
        },
      ];

      window.requestIdleCallback(workLoop, { timeout: 1000 });
      function workLoop(deadline) {
        console.log('每次任务的剩余时间: ' + deadline.timeRemaining());
        // 空闲或者超时的时候就调用任务
        while (
          (deadline.timeRemaining() > 0 || deadline.didTimeout) &&
          works.length > 0
        ) {
          performUnitWork();
        }

        if (works.length) {
          window.requestIdleCallback(workLoop, { timeout: 1000 });
        }
      }
      function performUnitWork() {
        works.shift()();
      }
    </script>
  </body>
</html>
